﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Telerik.Web.UI.Common.Core-vsdoc.js" assembly="Telerik.Web.UI" />
/// <reference path="~/Clients/Scripts/jQuery/jquery-1.6.1-vsdoc.js"/>
/// <reference path="~/Clients/Scripts/jQuery/jquery-ui-1.8.13.custom.min.js"/>
/// <reference path="~/Clients/Scripts/jQuery/jquery.ajaxmanager-3.12.debug.js"/>
/// <reference path="~/Clients/Scripts/jQuery/jquery.json.debug.js"/>
/// <reference path="~/Clients/Scripts/jQuery/jquery.component.debug.js"/>
/// <reference path="~/Clients/Scripts/globals.debug.js"/>
/// <reference path="~/Clients/Scripts/utils.debug.js"/>
/// <reference path="~/Clients/Scripts/errorHandling.debug.js"/>
/// <reference path="~/Clients/Scripts/loadingPanels.debug.js"/>
/// <reference path="~/Clients/Scripts/common.debug.js"/>
/// <reference path="~/Clients/Scripts/jqueryLookup.debug.js"/>
/// <reference path="~/Clients/Scripts/url.debug.js"/>
/// <reference path="~/Clients/Scripts/queryObject.debug.js"/>

Type.registerNamespace("IRC.Pages.Cases");

IRC.Pages.Cases.NewCase = function (element) {
    IRC.Pages.Cases.NewCase.initializeBase(this, [element]);
    this._mainOwner;
    this._controlsHolder;

    this._onInitDelegate;
    this._onLoadDelegate;

    this._historyAM;
    this._NewCasesAM;

    this._Customers;
    this._FastProblems;
    this._PhoneSets;
    this._CaseTypes;
    this._NewCases;
    this._CurrentCustomer;
    this._CurrentModel;
    this._RepairOrderNumber;
}

IRC.Pages.Cases.NewCase.prototype = {
    _controls: function () {
        if (!this._controlsHolder) {
            this._controlsHolder = new (function (element) {
                this.jq = new GreeNova.JqueryLookup(element);
                this.RadAjaxLoadingPanel = new GreeNova.JqueryLookup(this.jq, "[id$='RadAjaxLoadingPanel']", true);

                this.PanelCase = new GreeNova.JqueryLookup(this.jq, "[id$='PanelCase']");
                this.PanelHistory = new GreeNova.JqueryLookup(this.jq, "[id$='PanelHistory']");

                this.RadComboBoxCustomer = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadComboBoxCustomer']", true);

                this.ImageButtonRemoveCustomer = new GreeNova.JqueryLookup(this.PanelCase, "[id$='ImageButtonRemoveCustomer']");
                this.ImageButtonNewModel = new GreeNova.JqueryLookup(this.PanelCase, "[id$='ImageButtonNewModel']");
                this.ImageButtonCustomerDetail = new GreeNova.JqueryLookup(this.PanelCase, "[id$='ImageButtonCustomerDetail']");



                this.PanelCustomerDetailEditDialog = new GreeNova.JqueryLookup(this.jq, "[id$='PanelCustomerDetail']");
                this.PanelCustomerDetailEditDialogWindow = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='PanelCustomerDetailDialogWindow']");

                this.PanelImeiHistoryDialog = new GreeNova.JqueryLookup(this.jq, "[id$='PanelImeiHistory']");
                this.PanelImeiHistoryOpenDialogWindow = new GreeNova.JqueryLookup(this.PanelImeiHistoryDialog, "[id$='PanelImeiHistoryDialogOpen']");

                this.TextBoxFirstName = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='TextBoxFirstName']");
                this.TextBoxLastName = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='TextBoxLastName']");
                this.TextBoxPhone = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='TextBoxPhone']");
                this.TextBoxEmail = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='TextBoxEmail']");

                this.LabelFirstNameValidator = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='LabelFirstNameValidator']");
                this.LabelLastNameValidator = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='LabelLastNameValidator']");
                this.LabelEmailValidator = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='LabelEmailValidator']");
                this.LabelPhoneValidator = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='LabelPhoneValidator']");

                this.ImageButtonEditCustomerOk = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='ImageButtonEditCustomerOk']");
                this.ImageButtonEditCustomerClose = new GreeNova.JqueryLookup(this.PanelCustomerDetailEditDialog, "[id$='ImageButtonEditCustomerClose']");

                this.CheckBoxUseCustomerAgain = new GreeNova.JqueryLookup(this.PanelCase, "[id$='CheckBoxUseCustomerAgain']");


                this.LabelResult = new GreeNova.JqueryLookup(this.PanelCase, "[id$='LabelResult']");

                this.NewModelEditDialog = new GreeNova.JqueryLookup(this.jq, "[id$='NewModelEditDialog']");
                this.NewModelEditDialogWindow = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='NewModelEditDialogWindow']");

                this.ImageButtonEditModelOk = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='ImageButtonEditModelOk']");
                this.ImageButtonEditModelClose = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='ImageButtonEditModelClose']");

                this.TextBoxManufacturer = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='TextBoxManufacturer']");
                this.TextBoxModel = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='TextBoxModel']");
                this.RadComboBoxManufacturer = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='RadComboBoxManufacturer']", true);

                this.LabelManufactureValidator = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='LabelManufactureValidator']");
                this.LabelModelValidator = new GreeNova.JqueryLookup(this.NewModelEditDialog, "[id$='LabelModelValidator']");

                this.RequiredFieldValidatorDescription = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RequiredFieldValidatorDescription']");

                this.TextBoxIMEI = new GreeNova.JqueryLookup(this.PanelCase, "[id$='TextBoxIMEI']");

                this.ImageButtonNewCaseSave = new GreeNova.JqueryLookup(this.PanelCase, "[id$='ImageButtonNewCaseSave']");
                this.ImageButtonClearCase = new GreeNova.JqueryLookup(this.PanelCase, "[id$='ImageButtonClearCase']");
                this.ImageButtonImeiHistory = new GreeNova.JqueryLookup(this.PanelCase, "[id$='ImageButtonImeiHistory']");
                this.TextBoxDescription = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadTextBoxDescription']");
                this.TextBoxEstimatedPrice = new GreeNova.JqueryLookup(this.PanelCase, "[id$='TextBoxEstimatedPrice']");
                this.TextBoxDeposit = new GreeNova.JqueryLookup(this.PanelCase, "[id$='TextBoxDeposit']", true);

                this.LabelRepairOrderNumberText = new GreeNova.JqueryLookup(this.PanelCase, "[id$='LabelRepairOrderNumberText']");


                this.RadComboFastProblem = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadComboFastProblem']", true);
                //this.RadComboCaseType = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadComboCaseType']", true);
                this.RadioButtonListCaseType = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadioButtonListCaseType']", true);
                this.RadComboBoxModel = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadComboBoxModel']", true);

                this.RadComboBoxDeviceCondition = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadComboBoxDeviceCondition']", true);

                this.RadComboBoxPhoneSet = new GreeNova.JqueryLookup(this.PanelCase, "[id$='RadComboBoxPhoneSet']", true);
                this.RadDatePickerEstimatedDateCompletion = new GreeNova.JqueryLookup(this.jq, "[id$='RadDatePickerEstimatedDateCompletion']", true);

                this.RadGridImeiHistory = new GreeNova.JqueryLookup(this.PanelImeiHistoryDialog, "[id$='RadGridImeiHistory']", true);
                this.RadGridHistory = new GreeNova.JqueryLookup(this.jq, "[id$='RadGridHistory']", true);

                this.RadToolTipManagerLog = new GreeNova.JqueryLookup(this.jq, "[id$='RadToolTipManagerLog']", true);
            })(this.get_element());
        }
        return this._controlsHolder;
    },

    initialize: function () {
        IRC.Pages.Cases.NewCase.callBaseMethod(this, 'initialize');

        Sys.Application.add_init(this._onInitDelegate = this._onInit.setCtx(this));
        Sys.Application.add_load(this._onLoadDelegate = this._onLoad.setCtx(this));
    },
    dispose: function () {
        Sys.Application.remove_load(this._onLoadDelegate);
        Sys.Application.remove_init(this._onInitDelegate);

        if (this._controlsHolder) {
            this._controlsHolder.ImageButtonNewCaseSave.jq().unbind();
            this._controlsHolder.ImageButtonRemoveCustomer.jq().unbind();

        }
        this._controlsHolder = null;

        IRC.Pages.Cases.NewCase.callBaseMethod(this, 'dispose');
    },

    get_mainOwner: function () {
        return this._mainOwner;
    },
    set_mainOwner: function (value) {
        this._mainOwner = value;
    },

    _onInit: function () {
        var controls = this._controls();

        controls.NewModelEditDialog.jq().dialog({
            bgiframe: true,
            autoOpen: false,
            modal: true,
            position: 'center',
            draggable: true,
            resizable: false,
            closeOnEscape: true,
            width: 450,
            height: 250,
            open: this._newModelEditDialog_open.setCtx(this),
            close: this._newModelEditDialog_close.setCtx(this)
        });

        controls.PanelImeiHistoryDialog.jq().dialog({
            bgiframe: true,
            autoOpen: false,
            modal: true,
            position: 'center',
            draggable: true,
            resizable: false,
            closeOnEscape: true,
            width: 850,
            height: 250,
            open: this._newModelEditDialog_open.setCtx(this),
            close: this._newModelEditDialog_close.setCtx(this)
        });

        controls.PanelCustomerDetailEditDialog.jq().dialog({
            bgiframe: true,
            autoOpen: false,
            modal: true,
            position: 'center',
            draggable: true,
            resizable: false,
            closeOnEscape: true,
            width: 450,
            height: 350,
            open: this._newModelEditDialog_open.setCtx(this),
            close: this._newModelEditDialog_close.setCtx(this)
        });

        controls.ImageButtonNewCaseSave.jq().click(function () { this.NewCaseSave(); } .setCtx(this, { epd: true }));
        controls.ImageButtonRemoveCustomer.jq().click(function () { this.ClearCustomer(); } .setCtx(this, { epd: true }));
        controls.ImageButtonClearCase.jq().click(function () { this.initializeData(); } .setCtx(this, { epd: true }));
        controls.ImageButtonImeiHistory.jq().click(function () { this.ImeiHistoryDialogOpen(); } .setCtx(this, { epd: true }));
        controls.ImageButtonNewModel.jq().click(function () { this.NewModelCreate(); } .setCtx(this, { epd: true }));
        controls.ImageButtonCustomerDetail.jq().click(function () { this.CustomerDetailOpen(); } .setCtx(this, { epd: true }));

        controls.ImageButtonEditCustomerOk.jq().click(function () { this._Customer_Save(); } .setCtx(this, { epd: true }));
        controls.ImageButtonEditCustomerClose.jq().click(function () { controls.PanelCustomerDetailEditDialog.jq().dialog('close'); } .setCtx(this, { epd: true }));

        controls.ImageButtonEditModelClose.jq().click(function () { controls.NewModelEditDialog.jq().dialog('close'); } .setCtx(this, { epd: true }));
        controls.ImageButtonEditModelOk.jq().click(function () { this._NewModel_Save(); } .setCtx(this, { epd: true }));
    },

    _onLoad: function () {
        var controls = this._controls();

        controls.RadComboBoxCustomer.component().add_selectedIndexChanged(this._radComboBoxCustomer_selectedIndexChanged.setCtx(this));
        //controls.RadComboBoxCustomer.component().add_dropDownClosed(this._radComboBoxCustomer_add_dropDownClosed.setCtx(this));
        controls.RadComboBoxCustomer.component().add_onClientBlur(this._radComboBoxCustomer_onClientBlur.setCtx(this));


        controls.RadComboFastProblem.component().add_selectedIndexChanged(this._radComboFastProblem_selectedIndexChanged.setCtx(this));
        controls.RadComboFastProblem.component().add_onClientBlur(this._radComboFastProblem_onClientBlur.setCtx(this));

        //controls.RadComboBoxModel.component().add_dropDownClosed(this._radComboBoxModel_add_dropDownClosed.setCtx(this));
        //controls.RadComboBoxModel.component().add_selectedIndexChanged(this._radComboBoxModel_selectedIndexChanged.setCtx(this));


        controls.RadComboBoxModel.component().add_onClientBlur(this._radComboBoxModel_add_onClientBlur.setCtx(this));
        //controls.RadComboBoxModel.component().add_textChange(this._radComboBoxModel_add_textChange.setCtx(this));
        //controls.RadComboBoxModel.component().add_itemsRequesting(this._radComboBoxModel_add_itemsRequesting.setCtx(this));
        //controls.RadComboBoxModel.component().add_itemsRequested(this._radComboBoxModel_add_itemsRequested.setCtx(this));


        controls.TextBoxManufacturer.jq().change(this._textBoxManufacturer_add_textChange.setCtx(this));

        controls.RadComboBoxManufacturer.component().add_textChange(this._radComboBoxManufacturer_add_textChange.setCtx(this));
        controls.RadComboBoxManufacturer.component().add_onClientBlur(this._radComboBoxManufacturer_add_onClientBlur.setCtx(this));
        controls.RadComboBoxManufacturer.component().add_selectedIndexChanged(this._radComboBoxManufacturer_selectedIndexChanged.setCtx(this));

        var gh = controls.RadGridHistory.component();
        gh.add_command(this._radGridHistory_command.setCtx(this));
        gh.add_rowDataBound(this._radGridHistory_rowDataBound.setCtx(this));

        
        this.updateHistory();
        this.loadBasicCustomers();

        
        this.loadFastProblem();
        this.loadDeviceCondition();
        
        //this.loadCaseTypes();
        this.loadModel();
        this.loadPhoneSets();


    },

    _CustomerEdit_ClearValidators: function () {
        var controls = this._controls();

        controls.LabelFirstNameValidator.jq().text('');
        controls.LabelLastNameValidator.jq().text('');
        controls.LabelEmailValidator.jq().text('');
        controls.LabelPhoneValidator.jq().text('');
    },

    _CustomerEdit_Validate: function () {
        var controls = this._controls();
        this._CustomerEdit_ClearValidators();
        var res = true;

        var name = controls.TextBoxFirstName.jq().val();
        var surname = controls.TextBoxLastName.jq().val();
        var phone = controls.TextBoxPhone.jq().val();
        var email = controls.TextBoxEmail.jq().val()


        if (!name) {
            controls.LabelFirstNameValidator.jq().text('Value cannot be empty.');
            res = false;
        }

        if (!surname) {
            controls.LabelLastNameValidator.jq().text('Value cannot be empty.');
            res = false;
        }

        if (!phone) {
            controls.LabelEmailValidator.jq().text('Value cannot be empty.');
            res = false;
        }

        if (!email) {
            controls.LabelPhoneValidator.jq().text('Value cannot be empty.');
            res = false;
        }

        return res;
    },

    _NewModelEdit_ClearValidators: function () {
        var controls = this._controls();
        controls.LabelManufactureValidator.jq().text('');
        controls.LabelModelValidator.jq().text('');
    },

    _NewModelEdit_Validate: function () {
        var controls = this._controls();
        this._NewModelEdit_ClearValidators();
        var res = true;
        
        val = controls.TextBoxManufacturer.jq().val();
        var man = controls.RadComboBoxManufacturer.component();
        var curManufacturer = man.get_value();

        if (!val && !curManufacturer) {
            controls.LabelManufactureValidator.jq().text('Value cannot be empty. Please select existing Manufacturer or add a new one.');
            res = false;
        }

        val = controls.TextBoxModel.jq().val();
        if (!val) {
            controls.LabelModelValidator.jq().text('Value cannot be empty.');
            res = false;
        }
        return res;
    },

    _NewModel_Save: function () {
        var controls = this._controls();
        if (!this._NewModelEdit_Validate())
            return;
        var lp = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.PanelCase);
        //var lp = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.NewModelEditDialog);

        var man = controls.RadComboBoxManufacturer.component();
        var curManufacturer = man.get_value();

        var am = this.get_NewCasesAM();
        am.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/NewModel_Save'),
            data: $.json.serialize({
                ExistingManufacturer: curManufacturer,
                NewManufacturer: controls.TextBoxManufacturer.jq().val(),
                NewModel: controls.TextBoxModel.jq().val()
            }),
            success: function (data, status, xhr) {
                var result = data.d;
                if (result) {
                    if (!result.Success) {
                        radalert(result.ErrorMessage, 500, 100, 'Error');
                    }
                    else {
                        controls.RadComboBoxModel.component().set_text(result.Data.FullName);
                        var mod = controls.RadComboBoxModel.component();
                        mod.set_value(result.Data.Id);
                        controls.NewModelEditDialog.jq().dialog('close');
                    }
                }
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
                lp.hide();
            } .setCtx(this)
        });
    },


    _newModelEditDialog_open: function () {

    },

    _newModelEditDialog_close: function () {
    },

    NewModelCreate: function (sender, args) {
        var controls = this._controls();
        controls.TextBoxManufacturer.jq().val('');
        controls.TextBoxModel.jq().val('');
        controls.RadComboBoxManufacturer.component().set_text("");
        var man = controls.RadComboBoxManufacturer.component();
        man.set_value("");

        controls.NewModelEditDialog.jq().dialog('open');
    },

    CustomerDetailOpen: function (sender, args) {
        var controls = this._controls();
        this._CustomerEdit_ClearValidators();
        controls.PanelCustomerDetailEditDialog.jq().dialog('open');
    },

    ImeiHistoryDialogOpen: function (sender, args) {
        var controls = this._controls();
        controls.PanelImeiHistoryDialog.jq().dialog('open');

        var gh1 = controls.RadGridImeiHistory.component();
        gh1.add_command(this._radGridImeiHistory_command.setCtx(this));
        gh1.add_rowDataBound(this._radGridImeiHistory_rowDataBound.setCtx(this));
        this.updateImeiHistory();


    },
    _Customer_Save: function () {
        var controls = this._controls();
        if (!this._CustomerEdit_Validate())
            return;
        var lp = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.PanelCase);
        //var lp = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.NewModelEditDialog);

        var cust = controls.RadComboBoxCustomer.component();
        var curCustomer = cust.get_value();

        var am = this.get_NewCasesAM();
        am.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Customer_Save'),
            data: $.json.serialize({
                guid: '',
                name: controls.TextBoxFirstName.jq().val(),
                surname: controls.TextBoxLastName.jq().val(),
                phone: controls.TextBoxPhone.jq().val(),
                email: controls.TextBoxEmail.jq().val()
            }),
            success: function (data, status, xhr) {
                var result = data.d;
                if (result) {
                    if (!result.Success) {
                        radalert(result.ErrorMessage, 500, 100, 'Error');
                    }
                    else {
                        controls.RadComboBoxCustomer.component().set_text(result.Data.FullName);
                        /*var mod = controls.RadComboBoxModel.component();
                        mod.set_value(result.Data.Id);       */
                        controls.PanelCustomerDetailEditDialog.jq().dialog('close');
                    }
                }
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
                lp.hide();
            } .setCtx(this)
        });
    },

    _radComboBoxModel_add_itemsRequesting: function (sender, args) {
        var controls = this._controls();
        var mod = controls.RadComboBoxModel.component();

        if (mod._filterText != "") {

        }

    },


    _radComboBoxModel_add_itemsRequested: function (sender, args) {

    },

    _textBoxManufacturer_add_textChange: function (sender, args) {

        var controls = this._controls();
        controls.RadComboBoxManufacturer.component().set_text("");

        var man = controls.RadComboBoxManufacturer.component();
        man.set_value("");
    },

    _radComboBoxManufacturer_add_textChange: function (sender, args) {
        var controls = this._controls();
        controls.TextBoxManufacturer.jq().val("");
    },

    _radComboBoxManufacturer_selectedIndexChanged: function (sender, args) {
        var controls = this._controls();
        controls.TextBoxManufacturer.jq().val("");
    },

    _radComboBoxManufacturer_add_onClientBlur: function (sender, args) {

        var controls = this._controls();
        var man = controls.RadComboBoxManufacturer.component();


        if (man._filterText != "") {
            if (man._originalText != man._filterText) {
                //controls.RadComboBoxManufacturer.component().set_text(man._originalText);
                //controls.TextBoxManufacturer.jq().val("");
            }
        }

    },

    _radComboBoxModel_add_onClientBlur: function (sender, args) {

        var controls = this._controls();
        var mod = controls.RadComboBoxModel.component();


        if (mod._filterText != "") {
            if (mod._originalText != mod._filterText) {
                controls.RadComboBoxModel.component().set_text(mod._originalText);
            }
        }

    },

    _radGridImeiHistory_rowDataBound: function (sender, args) {
        var item = args.get_item();
        var dataItem = args.get_dataItem();
        var arguments = new Object(2);
        arguments[0] = dataItem.RowGuid;
        arguments[1] = true;
        var cEdit = $(item.get_cell("UseDetail")).empty();
        if (!this._isLocked) {
            var eEdit = $('<a href="#">Use detail</a>').click(this._caseEdit.setCtx(this, { epd: true, fargs: arguments }));
            cEdit.append(eEdit);
        }
    },

    _radGridHistory_rowDataBound: function (sender, args) {
        var item = args.get_item();
        var dataItem = args.get_dataItem();
        arguments[0] = dataItem.RowGuid;
        arguments[1] = false;
        var cEdit = $(item.get_cell("Edit")).empty();
        if (!this._isLocked) {
            var f = false;
            var eEdit = $('<a href="#">Edit</a>').click(this._caseEdit.setCtx(this, { epd: true, fargs: arguments }));
            cEdit.append(eEdit);
        }
    },

    _caseEdit: function (arguments) {

        var controls = this._controls();
        var lpCases = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.PanelCase);
        var lpHistory = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.PanelHistory);

        var am = this.get_NewCasesAM();
        am.clear(true);
        am.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Case_GetForEdit'),
            data: $.json.serialize({
                caseRowGuid: arguments[0],
                isHistory: arguments[1],
            }),
            success: function (data, status, xhr) {
                var res = data.d;
                debugger;
                if (res) {
                    if (res.Success) {
                        var result = res.Data;
                        this._set_DataFromResult(result);
                        if (result.isHistory==true) {
                            controls.PanelImeiHistoryDialog.jq().dialog('close');
                        }
                    }
                }
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                debugger;
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
                lpCases.hide();
                lpHistory.hide();
            } .setCtx(this)
        });
    },

    _set_DataFromResult: function (result) {
        var controls = this._controls();
        var useCustomerAgain = controls.CheckBoxUseCustomerAgain.jq().prop('checked');

        if (result.CustomerId != null) {
            var cus = controls.RadComboBoxCustomer.component();
            var c = cus.findItemByValue(result.CustomerId);
            if (c) c.select();
        }
        else {
            if (!useCustomerAgain)
                this.ClearCustomer();
        }

        var dev = controls.RadComboBoxDeviceCondition.component();
        var d = dev.findItemByValue(result.DeviceConditionId);
        if (d) d.select();

        if (result.currentModel != null) {
            controls.RadComboBoxModel.component().set_text(result.currentModel.FullName);

            var mod = controls.RadComboBoxModel.component();
            mod.set_value(result.currentModel.Id);
        }
        else
            controls.RadComboBoxModel.component().set_text("");
        if(result.isHistory==true)
            this._RepairOrderNumber = "";
        else
            this._RepairOrderNumber = result.RepairOrderNumber;

        controls.TextBoxDescription.jq().val(result.Description);
        controls.TextBoxDeposit.component().set_value(result.Deposit);
        controls.TextBoxEstimatedPrice.jq().val(result.EstimatedPrice);
        controls.TextBoxIMEI.jq().val(result.IMEI);
        controls.RadDatePickerEstimatedDateCompletion.component().set_selectedDate(GreeNova.Utils.fromServerDateStr(result.EstimatedDateCompletion));
        debugger;
        ps = controls.RadComboBoxPhoneSet.component();
        ps.select_itemsByValue(result.PhoneSets);
    },

    _radComboFastProblem_onClientBlur: function (sender, args) {
        var controls = this._controls();
        controls.RadComboFastProblem.component().clearSelection();
    },

    _radComboFastProblem_selectedIndexChanged: function (sender, args) {
        var item = args.get_item();
        var dataItem = item.get_itemData();

        var controls = this._controls();

        if (dataItem) {
            controls.TextBoxDescription.jq().focus();
            controls.RadComboFastProblem.component().clearSelection();

            if (controls.TextBoxDescription.jq().val() == "")
                controls.TextBoxDescription.jq().val(dataItem.Name);
            else
                controls.TextBoxDescription.jq().val(controls.TextBoxDescription.jq().val() + ", " + dataItem.Name);

        }
        else {

        }

    },

    _radComboBoxModel_selectedIndexChanged: function (sender, args) {
        var item = args.get_item();

        var dataItem = item._text;

        if (dataItem) {
            this._CurrentModel = dataItem;
        }
        else {
            this._CurrentModel = null;
        }

    },

    _radComboBoxModel_add_dropDownClosed: function (sender, args) {

        var controls = this._controls();
        var mod = controls.RadComboBoxModel.component();

        if (!this._CurrentModel) {
            controls.RadComboBoxModel.component().clearSelection();
            this._CurrentModel = null;
        }
        else {
            if (mod._filterText != "") {
                if (mod._originalText != mod._filterText) {
                    controls.RadComboBoxModel.component().set_text(mod._originalText);
                }
            }
        }
    },

    _radComboBoxCustomer_onClientBlur: function (sender, args) {
        var controls = this._controls();
        var cus = controls.RadComboBoxCustomer.component();

        if (cus._filterText != "") {
            if (cus._originalText != cus._filterText) {
                controls.RadComboBoxCustomer.component().set_text(cus._originalText);
            }
            else
                controls.RadComboBoxCustomer.component().clearSelection();
        }
    },

    _radComboBoxCustomer_add_dropDownClosed: function (sender, args) {

        var controls = this._controls();
        var cus = controls.RadComboBoxCustomer.component();

        if (!this._CurrentCustomer) {
            controls.RadComboBoxCustomer.component().clearSelection();
            this._CurrentCustomer = null;
        }
        else {
            if (cus._filterText != "") {
                if (cus._originalText != cus._filterText) {
                    controls.RadComboBoxCustomer.component().set_text(cus._originalText);
                }
            }
        }
    },



    _radComboBoxCustomer_selectedIndexChanged: function (sender, args) {
        var item = args.get_item();

        var dataItem = item.get_itemData();

        var controls = this._controls();
        var cus = controls.RadComboBoxCustomer.component();

        if (dataItem) {
            controls.TextBoxFirstName.jq().val(dataItem.Name);
            controls.TextBoxLastName.jq().val(dataItem.Surname);
            controls.TextBoxPhone.jq().val(dataItem.Phone);
            controls.TextBoxEmail.jq().val(dataItem.Email);
            //this._CurrentCustomer = dataItem;
        }
        else {
            controls.TextBoxFirstName.jq().val('');
            controls.TextBoxLastName.jq().val('');
            controls.TextBoxPhone.jq().val('');
            controls.TextBoxEmail.jq().val('');
            //this._CurrentCustomer = null;
        }

    },


    _radGridHistory_command: function (sender, args) {
        args.set_cancel(true);
        this.updateHistory(true)
    },

    _radGridImeiHistory_command: function (sender, args) {
        debugger;
        args.set_cancel(true);
    },
    get_HistoryAM: function () {
        if (!this._historyAM)
            this._historyAM = GreeNova.Utils.AjaxManager.createForWS('_historyAM');
        return this._historyAM;
    },


    get_NewCasesAM: function () {
        if (!this._NewCasesAM)
            this._NewCasesAM = GreeNova.Utils.AjaxManager.createForWS('_NewCasesAM');
        return this._NewCasesAM;
    },

    updateImeiHistory: function () {
        
        var controls = this._controls();
        GreeNova.Utils.RadGrid.showStatusAjaxRequest(controls.RadGridImeiHistory);

        var ham = this.get_HistoryAM();
        ham.clear(true);
        ham.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/CasesImeiHistory_Get'),
            data: $.json.serialize({
                grid: GreeNova.Utils.RadGrid.getBindingInfo(controls.RadGridImeiHistory),
                imei: controls.TextBoxIMEI.jq().val()
            }),
            success: function (data, status, xhr) {

                var result = data.d;

                var gMT = controls.RadGridImeiHistory.component().get_masterTableView();

                GreeNova.Utils.RadGrid.bind(gMT, result.Count, result.Items);
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
                GreeNova.Utils.RadGrid.hideStatusAjaxRequest(controls.RadGridImeiHistory);
            } .setCtx(this)
        });
    },

    updateHistory: function () {
        var controls = this._controls();
        GreeNova.Utils.RadGrid.showStatusAjaxRequest(controls.RadGridHistory);

        var ham = this.get_HistoryAM();
        ham.clear(true);
        ham.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Cases_Get'),
            data: $.json.serialize({
                grid: GreeNova.Utils.RadGrid.getBindingInfo(controls.RadGridHistory)
            }),
            success: function (data, status, xhr) {

                var result = data.d;
                var ttm = controls.RadToolTipManagerLog.component();
                var gMT = controls.RadGridHistory.component().get_masterTableView();
                /*if (ttm) {
                $(gMT.get_element()).find("input.commentImageLogInfo").each(function (i, e) {
                var tooltip = ttm.getToolTipByElement(e);
                if (tooltip)
                tooltip.hide();
                });
                }*/
                GreeNova.Utils.RadGrid.bind(gMT, result.Count, result.Items);
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
                GreeNova.Utils.RadGrid.hideStatusAjaxRequest(controls.RadGridHistory);
            } .setCtx(this)
        });
    },

    historyLogInfoShow: function (targetElement, logID) {
        var controls = this._controls();
        var ttm = controls.RadToolTipManagerLog.component();
        if (!ttm) return;
        var tooltip = ttm.getToolTipByElement(targetElement);
        if (tooltip) {
            tooltip.show();
            return;
        }

        var pma = {
            LogID: logID
        };

        var ham = this.get_HistoryAM();
        ham.clear(true);
        ham.add({
            url: GreeNova.Globals.resolveUrl('ws/Common.asmx/LoggingInfo_Get'),
            data: $.json.serialize({
                logID: logID
            }),
            success: function (data, status, xhr) {
                var result = data.d;
                var tooltip = ttm.getToolTipByElement(targetElement);
                if (!tooltip)
                    tooltip = ttm.createToolTip(targetElement);
                tooltip.set_content(result);
                tooltip.show();
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this)
        });
    },

    loadDeviceCondition: function () {
        var controls = this._controls();
        //GreeNova.Utils.RadComboBox.showLoadingText(controls.RadComboBoxDeviceCondition);

        var tam = this.get_NewCasesAM();
        tam.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/DeviceConditions_Get'),
            data: null,
            success: function (data, status, xhr) {

                var result = data.d;
                this._FastProblems = result;
                GreeNova.Utils.RadComboBox.bind(controls.RadComboBoxDeviceCondition, result, 'Name', 'Id', null, result.length > 1);
                this.initializeData();
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
            } .setCtx(this)
        });
    },

    loadPhoneSets: function () {
        var controls = this._controls();
        var tam = this.get_NewCasesAM();
        tam.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/PhoneSets_Get'),
            data: null,
            success: function (data, status, xhr) {
            debugger;
            var result = data.d;
            
            var x = controls.RadComboBoxPhoneSet.component();
            x.bind(result, 'Name', 'ID');

            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
            } .setCtx(this)
        });
    },

    loadFastProblem: function () {
        var controls = this._controls();
        //GreeNova.Utils.RadComboBox.showLoadingText(controls.RadComboFastProblem);

        var tam = this.get_NewCasesAM();
        tam.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/FastProblem_Get'),
            data: null,
            success: function (data, status, xhr) {
            debugger;
                var result = data.d;
                this._FastProblems = result;
                GreeNova.Utils.RadComboBox.bind(controls.RadComboFastProblem, result, 'Name', 'Id', null, result.length > 1);

            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
            } .setCtx(this)
        });
    },
    /*
    loadStatus: function () {
    var controls = this._controls();
    //GreeNova.Utils.RadComboBox.showLoadingText(controls.RadComboBoxStatus);

    var tam = this.get_NewCasesAM();
    tam.add({
    url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Status_Get'),
    data: null,
    success: function (data, status, xhr) {

    var result = data.d;
    GreeNova.Utils.RadComboBox.bind(controls.RadComboBoxStatus, result, 'Name', 'Id', null, result.length > 1);

    } .setCtx(this),
    error: function (xhr, status, errorThrown, opt) {
    GreeNova.ErrorHandling.jqAMError(xhr, opt);
    } .setCtx(this),
    complete: function (xhr, status) {
    } .setCtx(this)
    });
    },*/



//    loadPhoneSets: function () {
//    debugger;
//    var controls = this._controls();
//    //GreeNova.Utils.RadComboBox.showLoadingText(controls.RadComboBoxPhoneSet);

//    var tam = this.get_NewCasesAM();
//    tam.add({
//    url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/PhoneSets_Get'),
//    data: null,
//    success: function (data, status, xhr) {
//     debugger;
//    var result = data.d;
//   
//    this._PhoneSets = result;

//    var x = controls.RadComboCheckTasks.component();
//    x.bind(result, 'Name', 'ID');
//    //GreeNova.Utils.RadComboBox.bind(controls.RadComboBoxPhoneSet, result, 'Name', 'Id', null, result.length > 1);

//    } .setCtx(this),
//    error: function (xhr, status, errorThrown, opt) {
//    GreeNova.ErrorHandling.jqAMError(xhr, opt);
//    } .setCtx(this),
//    complete: function (xhr, status) {
//    } .setCtx(this)
//    });
//    },


    loadModel: function () {
        /* var controls = this._controls();
        GreeNova.Utils.RadComboBox.showLoadingText(controls.RadComboBoxModel);

        var tam = this.get_NewCasesAM();
        tam.add({
        url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Model_Get'),
        data: null,
        success: function (data, status, xhr) {

        var result = data.d;
        this._FastProblems = result;
        GreeNova.Utils.RadComboBox.bind(controls.RadComboBoxModel, result, 'Name', 'Id', null, result.length > 1);

        } .setCtx(this),
        error: function (xhr, status, errorThrown, opt) {
        GreeNova.ErrorHandling.jqAMError(xhr, opt);
        } .setCtx(this),
        complete: function (xhr, status) {
        } .setCtx(this)
        });*/
    },

    /* loadCaseTypes: function () {
    var controls = this._controls();
    GreeNova.Utils.RadComboBox.showLoadingText(controls.RadComboCaseType);

    var tam = this.get_NewCasesAM();
    tam.add({
    url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/CaseType_Get'),
    data: null,
    success: function (data, status, xhr) {

    var result = data.d;
    this._CaseTypes = result;
    GreeNova.Utils.RadComboBox.bind(controls.RadComboCaseType, result, 'Name', 'Id', null, result.length > 1);

    } .setCtx(this),
    error: function (xhr, status, errorThrown, opt) {
    GreeNova.ErrorHandling.jqAMError(xhr, opt);
    } .setCtx(this),
    complete: function (xhr, status) {
    } .setCtx(this)
    });
    },*/

    initializeData: function () {
        var controls = this._controls();
        var lpCases = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.PanelCase);
        var am = this.get_NewCasesAM();
        am.clear(true);
        am.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Case_GetInitial'),
            data: null,
            success: function (data, status, xhr) {
                var res = data.d;
                if (res) {
                    if (res.Success) {
                        var result = res.Data;
                        this._set_DataFromResult(result);
                    }
                }
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
                lpCases.hide();
            } .setCtx(this)
        });
    },

    loadBasicCustomers: function () {
        var controls = this._controls();
        //GreeNova.Utils.RadComboBox.showLoadingText(controls.RadComboBoxCustomer);

        var tam = this.get_NewCasesAM();
        tam.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Customer_Get'),
            data: null,
            success: function (data, status, xhr) {

                var result = data.d;
                this._Customers = result;

                var npc = controls.RadComboBoxCustomer.component();

                GreeNova.Utils.RadComboBox.bind(controls.RadComboBoxCustomer, result, 'FullName', 'GuidId', null, result.length > 1);

                var sp = npc.get_selectedItem();
                /* var useCustomerAgain = controls.CheckBoxUseCustomerAgain.jq().prop('checked');
                if (useCustomerAgain) {

                if (sp) {
                var pnc = controls.RadComboBoxCustomer.component();
                var i = pnc.findItemByValue(this._CurrentCustomer.GuidId);
                if (i)
                i.select();
                }

                }*/

            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
            } .setCtx(this),
            complete: function (xhr, status) {
            } .setCtx(this)
        });
    },

    showResultNewCase: function (saved, aborted) {
        var controls = this._controls();
        if (saved)
            controls.LabelResult.jq().text("Case was saved").css({ 'color': 'green' }).show();
        else if (aborted)
            controls.LabelResult.jq().text("Request was aborted").css({ 'color': 'red' }).show();
        else
            controls.LabelResult.jq().text("Case was not saved").css({ 'color': 'red' }).show();
    },

    ClearCustomer: function () {
        var controls = this._controls();
        controls.RadComboBoxCustomer.component().clearSelection();
        controls.TextBoxFirstName.jq().val('');
        controls.TextBoxLastName.jq().val('');
        controls.TextBoxPhone.jq().val('');
        controls.TextBoxEmail.jq().val('');
    },

    NewCaseSave: function () {

        if (!Page_ClientValidate("NewCaseDetail")) {
            this.showResultNewCase();
            return;
        }

        if (!Page_ClientValidate("MailEdit"))
            return;

        var controls = this._controls();
        var lp = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.PanelCase);
        var am = this.get_NewCasesAM();

        am.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Case_Save'),
            data: $.json.serialize({
                newCaseSaveInfo: this._newCaseSave_NewCaseSaveInfo()

            }),
            success: function (data, status, xhr) {
                this.showResultNewCase(true);

                this._RepairOrderNumber = "";
                this.loadBasicCustomers();
                this.updateHistory();
                this.initializeData();
            } .setCtx(this),
            abort: function (xhr, status) {
                this.showResultNewCase(false, true);
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
                this.showResultNewCase();
            } .setCtx(this),
            complete: function (xhr, status) {
                lp.hide();
            } .setCtx(this)
        });
    },


    _newCaseSave_NewCaseSaveInfo: function () {

        var controls = this._controls();
        var customerGuid = null;
        if (controls.RadComboBoxCustomer.component().get_selectedItem()) {
            var customerData = controls.RadComboBoxCustomer.component().get_selectedItem().get_itemData();
            if (customerData)
                customerGuid = customerData.GuidId;
        }

        var curmodel = null;
        if (controls.RadComboBoxModel.component().get_selectedItem() == null) {
            var mod = controls.RadComboBoxModel.component();
            curmodel = mod.get_value();
        }
        else
            curmodel = controls.RadComboBoxModel.component().get_selectedItem().get_value()

        var res = {
            casetypeid: 1, //controls.RadioButtonListCaseType.jq().val(),

            modelguid: curmodel,
            statusid: 1, //controls.RadComboBoxStatus.component().get_selectedItem().get_itemData().Id,
            imei: controls.TextBoxIMEI.jq().val(),

            estimateddatecompletion: GreeNova.Utils.toServerDateStr(controls.RadDatePickerEstimatedDateCompletion.component().get_selectedDate()),
            DeviceConditionId: controls.RadComboBoxDeviceCondition.component().get_selectedItem().get_value(),
            estimatedprice: controls.TextBoxEstimatedPrice.jq().val(),
            deposit: controls.TextBoxDeposit.component().get_value(),
            casedescription: controls.TextBoxDescription.jq().val(),

            repairordernumber: this._RepairOrderNumber,
            phoneSets: controls.RadComboBoxPhoneSet.component().get_selectedValues(),

            customerguid: customerGuid,
            customername: controls.TextBoxFirstName.jq().val(),
            customersurname: controls.TextBoxLastName.jq().val(),
            customerphone: controls.TextBoxPhone.jq().val(),
            customeremail: controls.TextBoxEmail.jq().val()
        };

        return res;
    },

    showResultCustomer: function (saved, aborted) {
        var controls = this._controls();
        if (saved)
            controls.LabelResult.jq().text("Customer was saved").css({ 'color': 'green' }).show();
        else if (aborted)
            controls.LabelResult.jq().text("Request was aborted").css({ 'color': 'red' }).show();
        else
            controls.LabelResult.jq().text("Customer was not saved").css({ 'color': 'red' }).show();
    },

    CustomerSave: function () {

        if (!Page_ClientValidate("NewCase")) {
            this.showResultCustomer();
            return;
        }
        var controls = this._controls();
        var lp = GreeNova.LoadingPanels.show(controls.RadAjaxLoadingPanel, controls.PanelCase);

        var am = this.get_NewCasesAM();
        am.add({
            url: GreeNova.Globals.resolveUrl('ws/Cases.asmx/Customer_Save'),
            data: $.json.serialize({
                guid: controls.RadComboBoxCustomer.component().get_value(),
                name: controls.TextBoxFirstName.jq().val(),
                surname: controls.TextBoxLastName.jq().val(),
                phone: controls.TextBoxPhone.jq().val(),
                email: controls.TextBoxEmail.jq().val()

            }),
            success: function (data, status, xhr) {
                this.showResultCustomer(true);
                controls.TextBoxFirstName.jq().val('');
                controls.TextBoxLastName.jq().val('');
                controls.TextBoxPhone.jq().val('');
                controls.TextBoxEmail.jq().val('');
                this.loadBasicCustomers();
            } .setCtx(this),
            abort: function (xhr, status) {
                this.showResultCustomer(false, true);
            } .setCtx(this),
            error: function (xhr, status, errorThrown, opt) {
                GreeNova.ErrorHandling.jqAMError(xhr, opt);
                this.showResultCustomer();
            } .setCtx(this),
            complete: function (xhr, status) {
                lp.hide();
            } .setCtx(this)
        });
    }
}
IRC.Pages.Cases.NewCase.registerClass('IRC.Pages.Cases.NewCase', Sys.UI.Control);
